<template>
  <div>
    <pl-table
      style="width: 100%,overflow: hidden"
      :data="labelList"
      :row-class-name="rowClassName"
      :row-key="className"
      class="endSessionTable"
      size="mini"
    >
      <pl-table-column label="结束会话类别名称" class="label-name">
        <template scope="scope">
          <div
            class="row_line"
            :class="{
              row_tr_2: scope.row.level === 2,
              row_tr_3: scope.row.level === 3,
              row_tr_4: scope.row.level === 4,
              row_tr_5: scope.row.level === 5
            }"
          >
            <!-- <span class="drag"
              ><i class="iconfont icon-shunxutuozhuai"></i
            ></span> -->
            <span
              class="do_icon"
              @click.stop="showLabel(scope.$index, scope.row)"
              v-show="!scope.row.status"
            >
              <i
                :class="
                  scope.row.level === 5
                    ? ''
                    : scope.row.flag
                    ? 'icon iconfont icon-zuixiaohua'
                    : 'icon iconfont icon-zhankai'
                "
              ></i>
            </span>
            <span style="margin-left: 10px" v-if="!scope.row.status">{{
              scope.row.name
            }}</span>
            <span
              v-if="scope.row.status"
              :class="{ is_error: addBorderFlag === true }"
            >
              <el-input
                v-model.trim="scope.row.name"
                placeholder="输入字数限制在30字以内"
                :maxlength="30"
                class="edit_end_session_input"
                style="width: 170px; display: inline-block"
              ></el-input>
              <div style="display: inline-block" class="addLabel">
                <span @click.stop="handleChannel(scope.$index, scope.row)"
                  >取消</span
                ><span @click.stop="handleSave(scope.$index, scope.row)"
                  >保存</span
                >
              </div>
            </span>
          </div>
        </template>
      </pl-table-column>
      <pl-table-column label="状态" class="label-name">
        <template scope="scope">
          <div>
            <span class="stopStatus" v-show="scope.row.stateShow === '1'"
              >停用</span
            >
            <span v-show="scope.row.stateShow === '2'">启用</span>
          </div>
        </template>
      </pl-table-column>
      <pl-table-column label="操作" width="300px">
        <template scope="scope">
          <div v-show="scope.row.name && !scope.row.status" class="operate-btn">
            <span @click.stop="handleEdit(scope.$index, scope.row)">编辑</span>
            <span
              @click.stop="handleAddLabel(scope.$index, scope.row, '2')"
              v-show="scope.row.level === 1"
              >添加二级标签</span
            >
            <span
              @click.stop="handleAddLabel(scope.$index, scope.row, '3')"
              v-show="scope.row.level === 2"
              >添加三级标签</span
            >
            <span
              @click.stop="handleAddLabel(scope.$index, scope.row, '4')"
              v-show="scope.row.level === 3"
              >添加四级标签</span
            >
            <span
              @click.stop="handleAddLabel(scope.$index, scope.row, '5')"
              v-show="scope.row.level === 4"
              >添加五级标签</span
            >
            <span
              @click.stop="handleDisabled(scope.$index, scope.row, 'open')"
              v-show="scope.row.stateShow === '1'"
              >启用</span
            >
            <span
              class="stopBtn"
              @click.stop="handleDisabled(scope.$index, scope.row, 'stop')"
              v-show="scope.row.stateShow === '2'"
              >停用</span
            >
            <!-- <span @click.stop="handleDisabled(scope.$index, scope.row)" class="delete">删除</span> -->
          </div>
        </template>
      </pl-table-column>
    </pl-table>
  </div>
</template>
<script>
import { deepClone } from '@utils/m7Utils.js'
import Sortable from "sortablejs";
export default {
  name: 'webchatEndSessionTree',
  //    stopAddFlag     当正在编辑添加的时候不让进行别的操作
  //    addBorderFlag   为true是正在编辑
  data () {
    return {
      list: [],
      maxLevel: 0,
      stopAddFlag: false,
      addBorderFlag: false,
      loading2: false,
      oldList: []
    }
  },
  props: {
    tableData: {
      type: Array,
      default () {
        return []
      }
    },
    searchLabelName: {
      type: String,
      default: ''
    },
    searchLabelRandom: {
      type: Number,
      default: 0
    },
    doAddRandom: {
      type: Number,
      default: 0
    },
    refreshflag: {
      type: Number,
      default: 0
    },
    screening: {
      type: String,
      defalut: 'all'
    }
  },
  watch: {
    //      监控数据变化，进行搜索数据
    searchLabelRandom () {
      this.searchLabel()
    },
    refreshflag (newFlag, old) {
      if (newFlag < 1 && newFlag > 0) {
        this.refreshTable(() => {
          this.searchLabel()
        })
      } else if (newFlag > 1) {
        this.stopAddFlag = false
        this.addBorderFlag = false
        this.refreshTable(() => {
          this.searchLabel()
        })
      }
    },
    tableData () {
      this.list = this.tableData.filter(item => {
        return item.level === 1
      })
    },
    doAddRandom () {
      this.handleAddOneLabel()
    }
  },
  methods: {
    //     搜索标签，控制一级标签的显示隐藏
    searchLabel () {
      let flag = false
      this.labelList.forEach((item) => {
        if (item.status) {
          flag = true
        }
      })
      if (flag) {
        this.$message.error('编辑或添加结束类型时，不允许搜索！')
        return
      }
      this.labelList.forEach((item) => {
        if ((item.level === 1) && document.getElementsByClassName(item.keyStr + '').length) {
          document.getElementsByClassName(item.keyStr + '')[0].style.display = 'table-row'
        }
      })
      let nextarray = []
      let KeyStr = []
      nextarray = this.labelList.filter((item) => {
        if (item.name.indexOf(this.searchLabelName) !== -1) {
          return item
        }
      })
      let n = []
      nextarray.forEach((item) => {
        KeyStr.push(item.keyStr.split('-')[0])
      })
      KeyStr.forEach((item) => {
        if (n.indexOf(item) === -1) {
          n.push(item)
        }
      })
      for (var i = 0; i < this.labelList.length; i++) {
        this.maxLevel = this.labelList[i].level > this.maxLevel ? this.labelList[i].level : this.maxLevel
        if (this.labelList[i].level !== 1 && document.getElementsByClassName(this.labelList[i].keyStr + '').length) {
          document.getElementsByClassName(this.labelList[i].keyStr + '')[0].style.display = 'none'
        }
        this.labelList[i].flag = false
      }
      this.labelList.forEach((item) => {
        if (n.indexOf(item.keyStr) === -1 && (item.level === 1) && document.getElementsByClassName(item.keyStr + '').length) {
          document.getElementsByClassName(item.keyStr + '')[0].style.display = 'none'
        }
      })
    },
    //      展开
    unfolded (index, row, flag) {
      let nextarray = []
      let arr = this.tableData
      if (!flag) {
        let count = 0
        arr.forEach((item, arrIndex) => {
          if (item.level > 1) {
            let a = item.keyStr.split('-')
            let str = ''
            for (let i = 0; i < row.level; i++) {
              str += a[i] + '-'
            }
            if (row.keyStr === str.substring(0, str.length - 1) && item.level === row.level + 1) {
              count++
              this.labelList.splice((index + count), 0, item)
            }
          }
        })
      }
      nextarray = this.labelList.filter((item) => {
        let a = item.keyStr.split('-')
        let str = ''
        for (let i = 0; i < row.level; i++) {
          str += a[i] + '-'
        }
        return item.keyStr.length > row.keyStr.length && (str.substring(0, str.length - 1) === row.keyStr) && item.level === row.level + 1
      })
      nextarray.forEach((label) => {
        this.$nextTick(() => {
          document.getElementsByClassName(label.keyStr)[0].style.display = 'table-row'
        })
      })
      row.flag = true
    },
    //      收起
    folded (index, row) {
      // 收起下级
      let arr = this.labelList
      let i = arr.length
      while (i--) {
        let a = arr[i].keyStr.split('-')
        let str = ''
        for (let j = 0; j < row.level; j++) {
          str += a[j] + '-'
        }
        if (arr[i].level > 1 && row.keyStr === str.substring(0, str.length - 1) && arr[i].keyStr.length > row.keyStr.length) {
          arr[i].flag = false
          this.labelList.splice(i, 1)
        }
      }
      row.flag = false
    },
    //      添加一级标签
    handleAddOneLabel () {
      if (this.stopAddFlag) {
        this.addBorderFlag = true
        return
      }
      this.stopAddFlag = true
      //        level 1级
      //        flag 控制加减号
      let obj = {
        keyStr: '',
        key: '',
        level: 1,
        name: '',
        lastLevel: '',
        status: true,
        flag: false
      }
      this.list.push(obj)
      this.inputFocus()
    },
    //      添加二级／三级标签
    handleAddLabel (index, row, leavelNum) {
      if (this.stopAddFlag) {
        this.addBorderFlag = true
        return
      }
      this.stopAddFlag = true
      this.unfolded(index, row, 'flag')
      let nextarr = []
      nextarr = this.labelList.filter((item) => {
        // 加上 '-' 匹配是因为，如果下标是0-1 点击添加三级标签的时候，如果有大于0-10的数据 就会跑到最下面
        return item.keyStr.length > row.keyStr.length && item.keyStr.indexOf(row.keyStr + '-') !== -1
      })
      let insertIndex = 0
      let keyStr = []
      if (nextarr.length !== 0) {
        for (let i = 0; i < this.labelList.length; i++) {
          if (nextarr[nextarr.length - 1].keyStr === this.labelList[i].keyStr) {
            insertIndex = i
            keyStr = this.labelList[i].keyStr.split('-')
            break
          }
        }
      } else {
        keyStr = row.keyStr.split('-')
        insertIndex = index
      }
      let obj = {
        keyStr: '',
        key: '',
        level: leavelNum,
        name: '',
        lastLevel: row.levelStr,
        status: true,
        flag: false
      }
      if (row.level === 1) {
        obj.keyStr = keyStr.length > 1 ? keyStr[0] + '-' + (parseInt(keyStr[1]) + 1) : keyStr[0] + '-' + 1
      } else if (row.level === 2) {
        obj.keyStr = keyStr.length > 2 ? keyStr[0] + '-' + keyStr[1] + '-' + (parseInt(keyStr[2]) + 1) : keyStr[0] + '-' + keyStr[1] + '-' + 1
      } else if (row.level === 3) {
        obj.keyStr = keyStr.length > 3 ? keyStr[0] + '-' + keyStr[1] + '-' + keyStr[2] + '-' + (parseInt(keyStr[3]) + 1) :
          keyStr[0] + '-' + keyStr[1] + '-' + keyStr[2] + '-' + 1
      } else if (row.level === 4) {
        obj.keyStr = keyStr.length > 4 ? keyStr[0] + '-' + keyStr[1] + '-' + keyStr[2] + '-' + keyStr[3] + '-' + (parseInt(keyStr[4]) + 1) :
          keyStr[0] + '-' + keyStr[1] + '-' + keyStr[2] + '-' + keyStr[3] + '-' + 1
      }
      this.labelList.splice(insertIndex + 1, 0, obj)
      this.inputFocus()
      //        this.labelList.push(obj)
    },
    //      取消操作
    handleChannel (index, row) {
      this.stopAddFlag = false
      this.addBorderFlag = false
      row.key ? row.status = false : this.labelList.splice(index, 1)
    },
    rowClassName ({ row, index }) {
      return '' + row.keyStr
    },
    //      通过keyStr添加唯一的className
    className (row, index) {
      return '' + row.keyStr
    },
    //      展开／收起操作
    showLabel (index, row) {
      let flag = false
      if (row.flag) {
        this.labelList.forEach((item) => {
          if (item.key === '' || item.status === true) {
            if (row.keyStr.split('-').length < item.keyStr.split('-').length) {
              let _data = item.keyStr.substring(0, item.keyStr.lastIndexOf('-'))
              if (_data.indexOf(row.keyStr) !== -1) {
                flag = true
              }
            }
          }
        })
        if (flag) {
          return
        }
        this.folded(index, row)
      } else {
        this.unfolded(index, row)
      }
      this.oldList = deepClone(this.labelList)
    },
    //      编辑标签
    handleEdit (index, row) {
      if (this.stopAddFlag) {
        this.addBorderFlag = true
        return
      }
      row.status = true
      this.stopAddFlag = true
      this.inputFocus()
    },
    //      删除
    handleDisabled (index, row, flag) {
      let num = 0
      this.labelList.forEach((item) => {
        let arr = item.keyStr.split('-')
        if (arr.length < 2) {
          ++num
        }
      })
      //        一级结束标签不得少于一条
      if (num < 2 && index === 0 && flag !== 'open') {
        this.$message.error('必须保留一条结束会话类别')
        return
      }
      let title = '该项及其子项都会停用，确定停用吗'
      if (flag === 'open') {
        title = '该项及其子项都会启用，确定启用吗'
      }
      this.$confirm(title, this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        this.oldList = deepClone(this.labelList)
        this.$emit('save', row, flag)
      })
    },
    //      刷新table
    refreshTable (callback) {
      this.$nextTick(() => {
        for (var i = 0; i < this.labelList.length; i++) {
          this.maxLevel = this.labelList[i].level > this.maxLevel ? this.labelList[i].level : this.maxLevel
          this.labelList[i].flag = false
          this.labelList[i].status = false
          if (this.labelList[i].level !== 1) {
            if (document.getElementsByClassName(this.labelList[i].keyStr + '')[0]) {
              document.getElementsByClassName(this.labelList[i].keyStr + '')[0].style.display = 'none'
              document.getElementsByClassName(this.labelList[i].keyStr + '')[0].className += (' level' + this.labelList[i].level)
            }
          }
        }
        for (var k = 0; k < this.labelList.length; k++) {
          let that = this
          that.oldList.forEach((item) => {
            if (item.key === that.labelList[k].key) {
              that.labelList[k].flag = item.flag
              if (that.labelList[k].flag) {
                that.unfolded(0, that.labelList[k], 'flag')
              }
            }
          })
        }
        this.stopAddFlag = false
        this.addBorderFlag = false
        this.loading2 = false
        callback && callback()
      })
    },
    //      保存
    handleSave (index, row) {
      this.oldList = deepClone(this.labelList)
      console.log(row)
      this.$emit('save', row)
    },
    //      编辑框获得焦点
    inputFocus () {
      this.$nextTick(() => {
        document.getElementsByClassName('edit_end_session_input')[0].children[0].focus()
      })
    }
  },
  computed: {
    labelList () {
      return this.list
    }
  },
  beforeMount () {
    this.stopAddFlag = false
    this.addBorderFlag = false
  },
  mounted () {
    this.list = this.tableData.filter(item => {
      return item.level === 1
    })
    this.refreshTable()

    const tbody = document.querySelector(
      ".endSessionTable .el-table__body-wrapper tbody"
    );
    let that = this;
    Sortable.create(tbody, {
      handle: ".drag",
      onMove ({ dragged, related }) {
        // {dragged, related}
        let fromObj = that.labelList[dragged.rowIndex]
        let toObj = that.labelList[related.rowIndex]
        if (fromObj.level === toObj.level && fromObj.lastLevel === toObj.lastLevel) {
          return true
        } else {
          return false
        }
      },
      onEnd ({ oldIndex, newIndex }) {
        let fromObj = deepClone(that.labelList[oldIndex])
        let toObj = deepClone(that.labelList[newIndex])
        if (fromObj.level === toObj.level && fromObj.lastLevel === toObj.lastLevel) {
          that.$set(that.labelList, oldIndex)
          that.$set(that.labelList, newIndex, fromObj)
        }
        //  let fromObj = that.labelList[dragged.rowIndex]
        //  let toObj = that.labelList[related.rowIndex]
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
@import '../../../../../assets/common.styl'
.tree-table
  margin 10px 20px
.addLabel
  span
    cursor pointer
    color $c-main
    margin-left 10px
.row_padding
  padding-left 16px
.operate-btn
  color $c-main
  span
    margin-left 10px
    cursor pointer
.row_line
  display inline-block
.row_tr_2
  padding-left 26px
.row_tr_3
  padding-left 52px
.row_tr_4
  padding-left 78px
.row_tr_5
  padding-left 110px
.endSessionTable
  overflow hidden
.do_icon
  cursor pointer
.delete
  color $c-pink
.stopBtn
  color #ff6b6b
.stopStatus
  color #ff9100
</style>
